/**
 * main.js - TweetOlympic
 * -----------------------
 * @version 0.1 First implementation 
 * @author David Ronai aka Makio
 */

//================== GLOBAL VAR ==================
var TO = TO || { VERSION : '1' };

var mouseX = 0;
var mouseY = 0;

var screenWidth = $(window).width();
var screenHeight = $(window).width();
var windowHalfX = $(window).width()/2;
var windowHalfY = $(window).height()/2;	
var tanFOV, windowHeight;

var isWebGL = Detector.webgl;
var stats;

var container, camera, projector, scene, renderer, composer, clock, controls;
var ambientlight, lights = [];

var user, userName, userID, userMobile, imageUser;

var URL_SERVER = "http://91.121.173.169:3000";
var modelLoader;

//=================== INIT =======================

$(document).ready(function() 
{
	modelLoader = new ModelLoader();
	
	initRenderer();
	
	SceneTraveler.getInstance().init(container);
	
	stats = new Stats();
	stats.domElement.style.position = 'absolute';
	stats.domElement.style.top = '0px';
	$(container).append( stats.domElement );
	
	$("h1").mouseenter(function() {
		TweenLite.to($("h1 span"),.5,{css:{height:"44px"}, ease:Quad.easeOut} );
	}).mouseleave(function() {
		TweenLite.to($("h1 span"),.3,{css:{height:"0px"}, ease:Quad.easeOut} );
	});

	document.addEventListener( 'mousemove', onDocumentMouseMove, false );
	document.addEventListener( 'touchstart', onDocumentTouchStart, false );
	document.addEventListener( 'touchmove', onDocumentTouchMove, false );
	
	$.preLoadAllImages([
		'img/particle.png',
		'img/favicon.png'
		],onLoadComplete
	);
	
	SceneTraveler.getInstance().transitionTo(new ConnexionScene(camera, scene, renderer));
	
});

function initRenderer()
{
	container = document.createElement('div');
	$(container).attr("id","webgl");
	$("section").append(container);
	
	clock = new THREE.Clock();
	
	//same camera for all
	camera = new THREE.PerspectiveCamera( 75, 980 / 590, 1, 10000 );
	tanFOV = Math.tan( ( ( Math.PI / 180 ) * camera.fov / 2 ) );
	windowHeight = 590;
	
	camera.aspect = $(window).width() / Math.floor($(window).height()-$("header").height());
    camera.fov = ( 360 / Math.PI ) * Math.atan( tanFOV * ( $(window).height() / windowHeight ) );
    camera.updateProjectionMatrix();
	
	camera.position.z = 100;
	
	scene = new THREE.Scene();
	scene.add(camera);
	
	projector = new THREE.Projector();
	renderer = new THREE.WebGLRenderer({antialias: true, clearAlpha: 0, maxLights: 2, stencil: false });
	renderer.shadowMapEnabled = true;
	renderer.preserveDrawingBuffer  = false;
	renderer.setSize( $(window).width(), $(window).height()-$("header").height());
	
	//light 
	ambientlight = new THREE.AmbientLight( 0x111111 );
	scene.add( ambientlight );
	
	setupLightControl();
	$(container).height( Math.floor($(window).height()-$("header").height()) );
	$(container).append( renderer.domElement );
}

function removeAllLight()
{
	for(var i=lights.length-1; i>-1; i--){
		scene.remove( lights.pop() );
	}
}

function tweenMaterial(d, duration, params) {
	if(d.material!=undefined){
		TweenLite.to(d.material, duration, params);
	}
	if(d.materials!=undefined){
		for(var i=0; i<materials.length; i++){
			TweenLite.to(materials[i], duration, params);
		}
	}
	if(d.children != undefined){
		for(var i=0; i < d.children.length; i++){
			tweenMaterial(d.children[i], duration, params);
		}
	}
}

changeOpacity = function(d,o){
	if(d.material!=undefined){
		d.material.opacity = o;
	}
	if(d.materials!=undefined){
		for(var i=0; i<materials.length; i++){
			materials[i].opacity = 0;
		}
	}
	if(d.children != undefined){
		for(var i=0; i < d.children.length; i++){
			changeOpacity(d.children[i], o);
		}
	}
}

var mergedGeo;

optimizeMesh = function(d){
	if(d != undefined && d instanceof THREE.Mesh){
		d.doubleSided = false;
		THREE.GeometryUtils.merge(mergedGeo, d);
	}
	if(d.children != undefined){
		for(var i=0; i < d.children.length; i++){
			optimizeMesh(d.children[i]);
		}
	}
}

changeMaterial = function(d){
	if(d.material!=undefined){
		d.material=new THREE.MeshLambertMaterial({color:d.material.color.getHex()});
	}
	if(d.materials!=undefined){
		for(var i=0; i<d.materials.length; i++){
			d.materials[i]=new THREE.MeshLambertMaterial({color:d.materials[i].color.getHex()});
		}
	}
	if(d.children != undefined){
		for(var i=0; i < d.children.length; i++){
			changeMaterial(d.children[i]);
		}
	}
}

function updateLightPanelValue()
{
	$("#light select").empty();
	for(var i=0; i< lights.length; i++){
		var option = $(document.createElement('option'));
		option.val( i );
		option.html("light["+i+"]");
		
		$("#light select").append(option);
	}
	var l = lights[0];
	fillWith(l);
}

function fillWith( l )
{	
	$("#positionX").val(l.position.x);
	$("#positionY").val(l.position.y);
	$("#positionZ").val(l.position.z);
	if(l.target){
		$("#lightLookX").val(l.target.position.x);
		$("#lightLookY").val(l.target.position.y);
		$("#lightLookZ").val(l.target.position.z);
	}
	$("#color").val(l.color.getHex());
	$("#intensity").val(l.intensity);
	$("#exponent").val(l.exponent);
	$("#darkness").val(l.shadowDarkness);
	$("#cameraNear").val(l.shadowCameraNear);
	$("#cameraFar").val(l.shadowCameraFar);
	$("#cameraFov").val(l.shadowCameraFov);
	$("#shadowMapWidth").val(l.shadowMapWidth);
	$("#shadowMapHeight").val(l.shadowMapHeight);
}

function setLight( l )
{
	l.position.x = parseInt($("#positionX").val());
	l.position.y = parseInt($("#positionY").val());
	l.position.z = parseInt($("#positionZ").val());
	if(l.target){
		l.target.position.x = parseInt($("#lightLookX").val());
		l.target.position.y = parseInt($("#lightLookY").val());
		l.target.position.z = parseInt($("#lightLookZ").val());
	}
	l.color.setHex(parseInt("0x"+$("#color").val()));
	l.intensity = parseFloat($("#intensity").val());
	l.exponent = parseFloat($("#exponent").val());
	l.shadowDarkness = parseFloat($("#darkness").val());
	l.shadowCameraNear = parseInt($("#cameraNear").val());
	l.shadowCameraFar = parseInt($("#cameraFar").val());
	l.shadowCameraFov = parseInt($("#cameraFov").val());
	l.shadowMapWidth = parseInt($("#shadowMapWidth").val());
	l.shadowMapHeight = parseInt($("#shadowMapHeight").val());
}

function setupLightControl()
{
	$("#positionX, #positionY, #positionZ, #lightLookX, #lightLookY, #lightLookZ, #intensity, #exponent, #darkness, #cameraNear, #cameraFar, #cameraFov, #shadowMapWidth, #shadowMapHeight")
	.change(function(){ setLight(lights[parseInt($("#light select").val())]) });

	$('#color').ColorPicker({
		color: '#fffff',
		onSubmit: function(hsb, hex, rgb, el) {
			$(el).val(hex);
			$(el).ColorPickerHide();
			$(this).val(this.value);
		},
		onBeforeShow: function () {
			$(this).ColorPickerSetColor(this.value);
			setLight(lights[parseInt($("#light select").val())]);
		},
		onChange: function (hsb, hex, rgb) {
			$('#color').val(String(hex).toUpperCase());
			setLight(lights[parseInt($("#light select").val())]);
		}
	})
	.bind('keyup', function(){
		$(this).ColorPickerSetColor(this.value);
		setLight(lights[parseInt($("#light select").val())]);
	});
	
	$("#light select").change(function()
	{
		fillWith(lights[parseInt($("#light select").val())]);
	});
	
	$("#light #create").click(function()
	{
		addSpotlight();
		updateLightPanelValue();
		fillWith(lights[parseInt($("#light select").val())]);
	});

}

function addSpotlight( params )
{
	var color = params.color || 0xFFFFFF*Math.random();
	var light = new THREE.SpotLight( color );
	light.position.set( params.x, params.y, params.z );
	light.target.position.x = params.targetX || 0;
	light.target.position.y = params.targetY || 0;
	light.target.position.z = params.targetZ || 0;
	light.exponent = params.exponent || 10;
	light.castShadow = params.castShadow!=undefined ? params.castShadow : true;
	light.shadowCameraVisible =  params.visible!=undefined ? params.visible : true;
	light.intensity = params.intensity || 1;
	light.shadowDarkness = params.darkness || .3;
	light.shadowCameraNear = params.near || 1;
	light.shadowCameraFar =  params.far || 300;
	light.shadowCameraFov = params.fov || 50;
	light.shadowMapWidth = params.shadowMapWidth || 2048;
	light.shadowMapHeight = params.shadowMapHeight || 2048;
	
	scene.add(light);
	scene.add(light.target);
	lights.push(light);
}

function addPointLight(color,a,r,x,y,z)  {
	var light = new THREE.PointLight(color,a, r);
	light.position.x = x;
	light.position.y = y;
	light.position.z = z;
	scene.add( light );
	lights.push(light);
	return light;
}

function onLoadComplete()
{
	//start render loop
	animate(); 
}

//=================== LISTENERS =======================

$(window).resize(function() 
{
	screenWidth = $(window).width();
	screenHeight = $(window).width();
	windowHalfX = $(window).width()/2;
	windowHalfY = $(window).height()/2;
	
	renderer.setSize( $(window).width(), Math.floor( $(window).height()-$("header").height() ));
	
	$(container).height( Math.floor($(window).height()-$("header").height()) );
	//$(container).width( Math.floor($(window).width()));
	
    camera.aspect = $(window).width() / Math.floor($(window).height()-$("header").height());
    
    // adjust the FOV
    camera.fov = ( 360 / Math.PI ) * Math.atan( tanFOV * ( $(window).height() / windowHeight ) );
    
    camera.updateProjectionMatrix();
	
	if($(window).width()<980 || $(window).height()<590){
		$("section").hide();
		$("#wrapMin").show();
	} else {
		$("section").show();
		$("#wrapMin").hide();
	}
});

function onDocumentMouseMove(event) 
{
	mouseX = event.clientX - windowHalfX;
	mouseY = event.clientY - windowHalfY;
}

function onDocumentTouchStart( event ) 
{
	if ( event.touches.length > 1 ) {
		event.preventDefault();
		mouseX = event.touches[ 0 ].pageX - windowHalfX;
		mouseY = event.touches[ 0 ].pageY - windowHalfY;
	}
}

function onDocumentTouchMove( event ) 
{
	if ( event.touches.length == 1 ) {
		event.preventDefault();
		mouseX = event.touches[ 0 ].pageX - windowHalfX;
		mouseY = event.touches[ 0 ].pageY - windowHalfY;
	}
}

//=================== RENDER LOOP =======================

function animate() 
{
	requestAnimationFrame( animate );
	
	if(stats)
		stats.update();
		
	if(SceneTraveler.getInstance().getCurrentScene())
		SceneTraveler.getInstance().getCurrentScene().update();
	
	// DEBUG ONLY ======================================== [
	//if(!$('#CameraManual').is(':checked')) {
		//$('#cameraX').val(camera.position.x);
		//$('#cameraY').val(camera.position.y);
		//$('#cameraZ').val(camera.position.z);
		//$('#cameraRX').val(camera.rotation.x*180/Math.PI);
		//$('#cameraRY').val(camera.rotation.y*180/Math.PI);
		//$('#cameraRZ').val(camera.rotation.z*180/Math.PI);
	//}
	
	if(controls){
		var delta = clock.getDelta();
		controls.update( delta );
	}
	// ==================================== END DEBUG PART ]
	renderer.render( scene, camera );
}